package com.yanqu.road.web.controller.game;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.eChannelType;
import com.yanqu.road.entity.enums.eOrderProductType;
import com.yanqu.road.entity.enums.ePreChargeType;
import com.yanqu.road.entity.web.HttpJsonWebParam;
import com.yanqu.road.logic.bussiness.player.UserBussiness;
import com.yanqu.road.logic.bussiness.recharge.RechargeBussiness;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.enums.eOrderStatus;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.recharge.RechargeOrder;
import com.yanqu.road.entity.recharge.ThirdPartyRechargeOrder;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.server.helper.SignHelper;
import com.yanqu.road.server.manger.AppKeyMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.TokenOrderWhiteMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.MallRechargeConfigMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.utils.order.OrderHelper;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.road.web.WebServer;
import com.yanqu.road.web.controller.BaseJsonHttpServlet;
import com.yanqu.road.web.mgr.MallMgr;
import com.yanqu.road.webservice.invoke.GameWebServiceInvoke;
import org.apache.commons.codec.binary.Base64;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@WebServlet(urlPatterns = "/androidRecharge")
public class AndroidRecharge extends BaseJsonHttpServlet {

	private static Logger logger = LogManager.getLogger(AndroidRecharge.class.getName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.info("request androidRecharge");
		HttpJsonWebParam httpJsonWebParam = super.parseRequest(request);
		JSONObject paramObj = httpJsonWebParam.getParamObj();
		String extension;
		String platformOrderNo;
		String sdkOrderNo;
		int rechargeId;
		String productType;
		long amount;
		int ingots;
		String openId;
		int payType;
		long userId;
		int realIngots;
		int extraIngots;
		String sign;
		//3.7增加字段记录订单信息
		String currency;			//定价币种
		String realMoney;			//对账金额
		String realCurrency;		//对账的币种
		String localMoney;			//支付原币金额
		String localCurrency;		//支付原币币种
		String ltrRate;				//原币金额转对账金额汇率
		String newMoney;			//支付金额
		String tax;					//税率
		long productCoin;			//本次购买的游戏币数
		int device;					//设备类型
		String payChannel;			//支付渠道
		String couponMoney;			//优惠券
		String subscription;		//订阅信息
		String platformUserId;
		int subCoinType; 	// 拆单发放内容 0 游戏币 1 代币
		int extraCoinType;	// 加码发放内容 0 游戏币 1 代币
		String subCoinRatio;	// 拆单兑换比例
		String extraCoinRatio;	// 加码兑换比例
		String gid;//子游戏id
		String appId;//APPID
		String payMethod;//支付方式
		try{
			extension = paramObj.getString("extension");        //游戏内充值表示orderNo，第三方充值表示mallId
			platformOrderNo = paramObj.getString("orderID");
			sdkOrderNo = paramObj.getString("channelOrderID");
			rechargeId = paramObj.getIntValue("productID");
			productType = paramObj.getString("productType");
			amount = paramObj.getLongValue("money");
			ingots = paramObj.getIntValue("coin");
			openId = paramObj.getString("userID");
			payType = paramObj.getIntValue("payType");
			userId = paramObj.getLong("roleID");
			realIngots = paramObj.getIntValue("realCoin");
			extraIngots = paramObj.getIntValue("extraCoin");

			subCoinType = paramObj.getIntValue("subCoinType");

			extraCoinType = paramObj.getIntValue("extraCoinType");
			subCoinRatio = paramObj.getString("subCoinRatio");
			if (StringUtils.isNullOrEmpty(subCoinRatio)) {
				subCoinRatio = "";
			}
			extraCoinRatio = paramObj.getString("extraCoinRatio");
			if (StringUtils.isNullOrEmpty(extraCoinRatio)) {
				extraCoinRatio = "";
			}

			gid = paramObj.getString("gid");
			if (StringUtils.isNullOrEmpty(gid)) {
				gid = "";
			}
			appId = paramObj.getString("appid");
			if (StringUtils.isNullOrEmpty(appId)) {
				appId = "";
			}
			payMethod = paramObj.getString("pay_method");
			if (StringUtils.isNullOrEmpty(payMethod)) {
				payMethod = "";
			}

			sign = paramObj.getString("sign");


			currency = paramObj.getString("currency");
			realMoney = paramObj.getString("realMoney");
			if(StringUtils.isNullOrEmpty(realMoney)){
				realMoney = "0";
			}
			try {
				if ("0".equals(realMoney)) {
					BigDecimal tempValue = new BigDecimal(amount);
					tempValue = tempValue.divide(BigDecimal.valueOf(100), BigDecimal.ROUND_UP, 2);
					realMoney = tempValue.toString();
				}
			}catch (Exception e){
				logger.error("calc realMoney error:", e);
			}
			realCurrency = paramObj.getString("realCurrency");
			localMoney = paramObj.getString("localMoney");
			if(StringUtils.isNullOrEmpty(localMoney)){
				localMoney = "0";
			}
			localCurrency = paramObj.getString("localCurrency");
			ltrRate = paramObj.getString("ltrRate");
			if(StringUtils.isNullOrEmpty(ltrRate)){
				ltrRate = "0";
			}
			newMoney = paramObj.getString("newMoney");
			if(StringUtils.isNullOrEmpty(newMoney)){
				newMoney = "0";
			}
			tax = paramObj.getString("tax");
			if(StringUtils.isNullOrEmpty(tax)){
				tax = "0";
			}
			productCoin = paramObj.getLongValue("productCoin");
			device = paramObj.getIntValue("device");
			payChannel = paramObj.getString("payChannel");
			couponMoney = paramObj.getString("couponMoney");
			subscription = paramObj.getString("subscriptionNotification");
			if(!StringUtils.isNullOrEmpty(subscription)){
				subscription = new String(Base64.decodeBase64(subscription));
			}
			platformUserId = paramObj.getString("platformUserId");
		} catch (Exception e) {
			logger.error("recharge args error:" + e);
			sendResult(response, 0, "args error");
			return;
		}
		try{
			SortedMap<String, String> paramMap = SignHelper.getParamMap(paramObj);
			if(!SignHelper.checkSign(paramMap, AppKeyMgr.getAndroidAppSecret(), sign)){
				if(ServerListMgr.isCnMergeServer(WebServer.getInstance().getServerId())){
					if(!SignHelper.checkSign(paramMap, ChannelConfig.APP_SECRET_CONFIG, sign)){
						logger.error("androidRecharge sign error");
						sendResult(response, 0, "sign error");
						return;
					}
				}else {
					logger.error("androidRecharge sign error");
					sendResult(response, 0, "sign error");
					return;
				}
			}
			UserInfo userInfo = UserBussiness.getUserInfoByUserId(userId);
			if (null == userInfo) {
				logger.error("androidRecharge user no find,platformOrderNo:{},userId{}", platformOrderNo, userId);
				sendResult(response, 0, "role no find");
				return;
			}
			if (!Objects.equals(userInfo.getOpenId(), openId)) {
				logger.error("androidRecharge openId error,platformOrderNo:{},openId:{}; platformOpenId:{}", platformOrderNo, userInfo.getOpenId(), openId);
				if(!Objects.equals(userInfo.getPlatformUserId(), platformUserId)) {
					logger.error("androidRecharge platformUserId error,platformOrderNo:{},local platformUserId:{}; platformUserId:{}",
							platformOrderNo, userInfo.getPlatformUserId(), platformUserId);
					sendResult(response, 0, "dirty userId");
					return;
				}
			}
			if(payType == 1 || payType == 3) {//游戏内购、ios钱包
				if(Objects.equals(eOrderProductType.Subscription.getValue(), productType)) {//订阅
					subscribeRecharge(response, extension, platformOrderNo, sdkOrderNo, rechargeId, amount, openId, userId, payType, currency, realMoney,
							realCurrency, localMoney, localCurrency, ltrRate, newMoney, tax, productCoin, device, payChannel, couponMoney, productType,
							subscription, gid, appId, payMethod);
				}else {//直购
					gameRecharge(response, extension, platformOrderNo, sdkOrderNo, rechargeId, amount, openId, userId, payType, currency, realMoney,
							realCurrency, localMoney, localCurrency, ltrRate, newMoney, tax, productCoin, device, payChannel, couponMoney, productType,
							subscription, gid, appId, payMethod);
				}
			}else if(payType == 2){//第三方
				int mallId = 0;
				try {
					mallId = Integer.parseInt(extension);
				}catch (Exception e){
					logger.warn("recharge mallId args error:" + e);
				}
				thirdPartyRecharge(response, platformOrderNo, sdkOrderNo, mallId, productType, amount, ingots, openId, userId, realIngots,
						extraIngots, subCoinType, subCoinRatio, extraCoinType, extraCoinRatio, rechargeId, currency, realMoney, realCurrency, localMoney, localCurrency, ltrRate, newMoney, tax, productCoin,
						device, payChannel, couponMoney, gid, appId, payMethod);
			}else {
				logger.error("unknown payType:{}", payType);
				sendResult(response, 0, "unknown payType");
			}
		} catch (Exception e) {
			logger.error("recharge error:" + e);
			sendResult(response, 0, "other error");
		}
	}

	private void gameRecharge(HttpServletResponse response, String orderNo, String platformOrderNo, String sdkOrderNo, int rechargeId, long amount,
			String openId, long userId, int payType, String currency, String realMoney, String realCurrency, String localMoney, String localCurrency,
			String ltrRate, String newMoney, String tax, long productCoin, int device, String payChannel, String couponMoney, String productType,
			String subscription, String gid, String appId, String payMethod) {
		RechargeOrder rechargeOrder = RechargeBussiness.getRechargeOrder(orderNo);
		if (null == rechargeOrder) {
			logger.error("androidRecharge order no find,orderNo:{}", orderNo);
			sendResult(response, 0, "order no find");
			return;
		}
		if(rechargeOrder.getUserId() != userId){
			logger.error("androidRecharge order userId error,orderNo:{},local userId:{},platformUserId:{},payType:{}", orderNo,
                    rechargeOrder.getUserId(), userId, payType);
			sendResult(response, 0, "roleId error");
			return;
		}
		if (!rechargeOrder.getOrderStatus().equals(eOrderStatus.HasBeenCharged)) {
			rechargeOrder.setPlatformOrderNo(platformOrderNo);
			rechargeOrder.setSdkOrderNo(sdkOrderNo);
			rechargeOrder.setPayType(payType);
			rechargeOrder.setCurrency(currency);
			rechargeOrder.setRealMoney(realMoney);
			rechargeOrder.setRealCurrency(realCurrency);
			rechargeOrder.setLocalMoney(localMoney);
			rechargeOrder.setLocalCurrency(localCurrency);
			rechargeOrder.setLtrRate(ltrRate);
			rechargeOrder.setNewMoney(newMoney);
			rechargeOrder.setTax(tax);
			rechargeOrder.setProductCoin(productCoin);
			rechargeOrder.setDevice(device);
			rechargeOrder.setPayChannel(payChannel);
			rechargeOrder.setCouponMoney(couponMoney);
			if (OrderHelper.isTokensOrder(sdkOrderNo)) {//代币订单
				rechargeOrder.setOrderType(1);
			}
			rechargeOrder.setProductType(productType);
			rechargeOrder.setSubscription(subscription);
			rechargeOrder.setGid(gid);
			rechargeOrder.setAppid(appId);
			rechargeOrder.setPayMethod(payMethod);
			rechargeOrder.setPackageId(UserMgr.getUserPackageMark(userId));

			MallInfo mallInfo = MallMgr.getMallInfoByMallId(rechargeOrder.getMallId());
			if (null != mallInfo) {//商品不为空时间，校验一下信息一致性
				if(rechargeOrder.getCouponItemId() == 0) {//没有使用代金券
					if (rechargeId != mallInfo.getRechargeId()) {
						rechargeOrder.setOrderStatus(eOrderStatus.DirtyCharge);
						RechargeBussiness.updateRechargeOrder(rechargeOrder);
						logger.error("androidRecharge rechargeId error,orderNo:{};rechargeId:{}; platformRechargeId:{},payType:{}", orderNo,
								mallInfo.getRechargeId(), rechargeId, payType);
						sendResult(response, 0, "dirty productId");
						return;
					}
				}

				long mallMoney = MallRechargeConfigMgr.getPrice(mallInfo);
//				long mallMoney = Long.parseLong(mallInfo.getPrice());
				if(rechargeOrder.getCouponItemId() > 0){
					GoodsInfo couponGoods = GoodsMgr.getGoodsById(rechargeOrder.getCouponGoodsId());
					if(null == couponGoods){
						rechargeOrder.setOrderStatus(eOrderStatus.DirtyCharge);
						RechargeBussiness.updateRechargeOrder(rechargeOrder);
						logger.error("androidRecharge coupon goods not find,orderNo:{};couponItemId:{}; couponGoodsId:{}", orderNo,
								rechargeOrder.getCouponItemId(), rechargeOrder.getCouponGoodsId());
						sendResult(response, 0, "coupon not find");
						return;
					}
					long param1 = couponGoods.getParamList().get(0).longValue();
					if (mallMoney > amount + param1) {//收的钱小于定价
						rechargeOrder.setOrderStatus(eOrderStatus.DirtyCharge);
						RechargeBussiness.updateRechargeOrder(rechargeOrder);
						logger.error("androidRecharge amount error,orderNo:{};amount:{}; platformAmount:{},payType:{},couponItemId:{},couponGoodsId:{},couponSubPrice:{}",
								orderNo, mallMoney, amount, payType, rechargeOrder.getCouponItemId(), rechargeOrder.getCouponGoodsId(), param1);
						sendResult(response, 0, "dirty money");
						return;
					}
				}else {
					if (mallMoney > amount) {//收的钱小于定价
						rechargeOrder.setOrderStatus(eOrderStatus.DirtyCharge);
						RechargeBussiness.updateRechargeOrder(rechargeOrder);
						logger.error("androidRecharge amount error,orderNo:{};amount:{}; platformAmount:{},payType:{}", orderNo, mallMoney, amount, payType);
						sendResult(response, 0, "dirty money");
						return;
					}
				}
			}

			//校验金额
			if(rechargeOrder.getCouponItemId() <= 0) {//没使用代金券
				if (rechargeOrder.getAmount() > amount) {//收的钱小于定价
					rechargeOrder.setOrderStatus(eOrderStatus.DirtyCharge);
					RechargeBussiness.updateRechargeOrder(rechargeOrder);
					logger.error("androidRecharge 预订单金额不一致orderNo:{};preAmount:{}; nowAmount:{},payType:{}", orderNo, rechargeOrder.getAmount(), amount, payType);
					sendResult(response, 0, "dirty money");
					return;
				}
			}
			//判断代币
			if (OrderHelper.isTokensOrder(sdkOrderNo)) {//代币订单
				if (!TokenOrderWhiteMgr.isTokenOrderWhite(userId)) {//非白名单
					rechargeOrder.setOrderStatus(eOrderStatus.DirtyCharge);
					RechargeBussiness.updateRechargeOrder(rechargeOrder);
					logger.error("androidRecharge 代币订单，但非白名单,orderNo:{};userId:{}", orderNo, rechargeOrder.getUserId());
					sendResult(response, 0, "token order not white user");
					return;
				}
			}
			//游戏内到账
			rechargeOrder.setOrderStatus(eOrderStatus.ToBeCharged);
			if (RechargeBussiness.updateRechargeOrder(rechargeOrder)) {
				GameWebServiceInvoke.notifyRechargeSuccess(orderNo, 0);
			} else {
				logger.error("androidRecharge update order state fail,orderNo:{},payType:{}", orderNo, payType);
				sendResult(response, 0, "update order state fail");
				return;
			}
		}
		sendResult(response, 1, "success");
	}

	/**
	* 描述：订阅购买
	* 作者：zrq
	* 时间：2023/3/15
	* 参数：

	* 返回值：
	**/
	private void subscribeRecharge(HttpServletResponse response, String orderNo, String platformOrderNo, String sdkOrderNo, int rechargeId, long amount,
			  String openId, long userId, int payType, String currency, String realMoney, String realCurrency, String localMoney, String localCurrency,
			  String ltrRate, String newMoney, String tax, long productCoin, int device, String payChannel, String couponMoney, String productType,
			  String subscription, String gid, String appId, String payMethod) {
		if(StringUtils.isNullOrEmpty(subscription)){
			logger.error("subscribeRecharge order subscription is empty,orderNo:{},platformOrderNo:{},sdkOrderNo:{}",
					orderNo, platformOrderNo, sdkOrderNo);
			sendResult(response, 0, "order subscription is empty");
			return;
		}

		JSONObject dataObj = JSON.parseObject(subscription);
		int type = dataObj.getIntValue("type");
		String curSubscriptionOrderId = dataObj.getString("originalOrderID");
		if(StringUtils.isNullOrEmpty(curSubscriptionOrderId)){
			logger.error("subscribeRecharge order originalOrderID is empty,orderNo:{},platformOrderNo:{},sdkOrderNo:{},subscription:{}",
					orderNo, platformOrderNo, sdkOrderNo, subscription);
			sendResult(response, 0, "order subscription originalOrderID is empty");
			return;
		}
		if(0 == type){//新订阅
			RechargeOrder rechargeOrder = RechargeBussiness.getRechargeOrder(orderNo);
			if (null == rechargeOrder) {
				logger.error("subscribeRecharge order no find,orderNo:{},subscription:{}", orderNo, subscription);
				sendResult(response, 0, "order no find");
				return;
			}
			if(rechargeOrder.getUserId() != userId){
				logger.error("subscribeRecharge order userId error,orderNo:{},local userId:{},platformUserId:{},subscription:{}", orderNo,
						rechargeOrder.getUserId(), userId, subscription);
				sendResult(response, 0, "roleId error");
				return;
			}
			if(!curSubscriptionOrderId.equals(sdkOrderNo)){//不是新订阅，新订阅的订单号跟原始订单号要一致
				logger.error("subscribeRecharge order originalOrderID no same,orderNo:{},platformOrderNo:{},sdkOrderNo:{},curOriginalOrderID:{},subscription:{}",
						orderNo, platformOrderNo, sdkOrderNo, curSubscriptionOrderId, subscription);
				sendResult(response, 0, "order subscription originalOrderID no same");
				return;
			}

			MallInfo mallInfo = MallMgr.getMallInfoByMallId(rechargeOrder.getMallId());
			if (null != mallInfo) {//商品不为空时间，校验一下信息一致性
				if (rechargeId != mallInfo.getRechargeId()) {
					logger.error("subscribeRecharge rechargeId error,orderNo:{};rechargeId:{}; platformRechargeId:{},subscription:{}", orderNo,
							mallInfo.getRechargeId(), rechargeId, subscription);
					sendResult(response, 0, "dirty productId");
					return;
				}

				long mallMoney = MallRechargeConfigMgr.getPrice(mallInfo);
//				long mallMoney = Long.parseLong(mallInfo.getPrice());
				if (mallMoney > amount) {//收的钱小于定价
					BigDecimal bigTax = new BigDecimal(tax);
					BigDecimal totalAmount = bigTax.multiply(BigDecimal.valueOf(100)).add(BigDecimal.valueOf(amount));
					if(0 != totalAmount.compareTo(BigDecimal.valueOf(mallMoney))){
						logger.error("subscribeRecharge amount error,platformOrderNo:{},sdkOrderNo:{},amount:{},platformAmount:{},subscription:{}",
								platformOrderNo, sdkOrderNo, mallMoney, amount, subscription);
						sendResult(response, 0, "dirty money");
						return;
					}
				}
			}

			//校验金额
			if (rechargeOrder.getAmount() > amount) {//收的钱小于定价
				BigDecimal bigTax = new BigDecimal(tax);
				BigDecimal totalAmount = bigTax.multiply(BigDecimal.valueOf(100)).add(BigDecimal.valueOf(amount));
				if(0 != totalAmount.compareTo(BigDecimal.valueOf(rechargeOrder.getAmount()))){
					logger.error("subscribeRecharge 预订单金额不一致orderNo:{};preAmount:{}; nowAmount:{},subscription:{}", orderNo, rechargeOrder.getAmount(), amount, subscription);
					sendResult(response, 0, "dirty money");
					return;
				}
			}
			if(!StringUtils.isNullOrEmpty(rechargeOrder.getSubscription())){
				if(!Objects.equals(subscription, rechargeOrder.getSubscription())){
					logger.error("subscribeRecharge order new subscription but no same,orderNo:{},platformOrderNo:{},sdkOrderNo:{},curSubscription:{},oldSubscription:{}",
							orderNo, platformOrderNo, sdkOrderNo, subscription, rechargeOrder.getSubscription());
				}
				sendResult(response, 1, "success");
				return;
			}
			rechargeOrder.setPlatformOrderNo(platformOrderNo);
			rechargeOrder.setSdkOrderNo(sdkOrderNo);
			rechargeOrder.setPayType(payType);
			rechargeOrder.setCurrency(currency);
			rechargeOrder.setRealMoney(realMoney);
			rechargeOrder.setRealCurrency(realCurrency);
			rechargeOrder.setLocalMoney(localMoney);
			rechargeOrder.setLocalCurrency(localCurrency);
			rechargeOrder.setLtrRate(ltrRate);
			rechargeOrder.setNewMoney(newMoney);
			rechargeOrder.setTax(tax);
			rechargeOrder.setProductCoin(productCoin);
			rechargeOrder.setDevice(device);
			rechargeOrder.setPayChannel(payChannel);
			rechargeOrder.setCouponMoney(couponMoney);
			rechargeOrder.setProductType(productType);
			rechargeOrder.setSubscription(subscription);
			rechargeOrder.setGid(gid);
			rechargeOrder.setAppid(appId);
			rechargeOrder.setPayMethod(payMethod);
			rechargeOrder.setPackageId(UserMgr.getUserPackageMark(userId));

			//游戏内到账
			rechargeOrder.setOrderStatus(eOrderStatus.ToBeCharged);
			if (!RechargeBussiness.updateSubscribeRechargeOrder(rechargeOrder)) {
				logger.error("subscribeRecharge update order state fail,orderNo:{},payType:{}", orderNo, payType);
				sendResult(response, 0, "update order state fail");
				return;

			}
			GameWebServiceInvoke.notifyRechargeSuccess(orderNo, 0);
			sendResult(response, 1, "success");
		}else if(1 == type){//续订
			RechargeOrder rechargeSdkOrder = RechargeBussiness.getRechargeOrderBySdkOrderNo(sdkOrderNo);
			if(null != rechargeSdkOrder){//已经入库的订单，定为重复订单，直接返回
				if(!Objects.equals(rechargeSdkOrder.getPlatformOrderNo(), platformOrderNo)){
					logger.error("subscribeRecharge repeat notify,local platformOrderNo:{},platformOrderNo{},sdkOrderNo:{},subscription:{}",
							rechargeSdkOrder.getPlatformOrderNo(), platformOrderNo, sdkOrderNo, subscription);
				}
				sendResult(response, 1, "success");
				return;
			}
			RechargeOrder firstRechargeOrder = RechargeBussiness.getRechargeOrderBySdkOrderNo(curSubscriptionOrderId);
//			if (null == firstRechargeOrder) {
//				logger.error("subscribeRecharge first order no find,platformOrderNo:{},sdkOrderNo:{},subscription:{}",
//						platformOrderNo, sdkOrderNo, subscription);
//				sendResult(response, 0, "order no find");
//				return;
//			}
			int mallId = 0;
			long returnIngots = 0;
			int vipExp = 0;
			int shopType = 0;
			String mallName = "";
			int mallMarkId = 0;
			if(null != firstRechargeOrder){
				if(firstRechargeOrder.getUserId() != userId){
					logger.error("subscribeRecharge order userId error,platformOrderNo:{},sdkOrderNo:{},local userId:{},platformUserId:{},subscription:{}",
							platformOrderNo, sdkOrderNo, firstRechargeOrder.getUserId(), userId, subscription);
					sendResult(response, 0, "roleId error");
					return;
				}
				mallId = firstRechargeOrder.getMallId();
				returnIngots = firstRechargeOrder.getReturnIngots();
				vipExp = firstRechargeOrder.getAddVipExp();
				shopType = firstRechargeOrder.getShopType();
				mallName = firstRechargeOrder.getMallName();
				mallMarkId = firstRechargeOrder.getMallMarkId();
			}else {
				try {
					mallId = Integer.parseInt(orderNo);    //orderNo是extension
					MallInfo mallInfo = MallMgr.getMallInfoByMallId(mallId);
					if (mallInfo == null) {
						logger.error("subscribeRecharge order userId error,platformOrderNo:{},sdkOrderNo:{},platformUserId:{},subscription:{}",
								platformOrderNo, sdkOrderNo, userId, subscription);
						sendResult(response, 0, "extension to mallId error");
						return;
					}
				} catch (Exception e){
					logger.error("recharge mallId args error:" + e);
					sendResult(response, 0, "extension to mallId error");
					return;
				}
			}

			MallInfo mallInfo = MallMgr.getMallInfoByMallId(mallId);
			long mallMoney = 0;
			if (null != mallInfo) {//商品不为空时间，校验一下信息一致性
				if (rechargeId != mallInfo.getRechargeId()) {
					logger.error("subscribeRecharge rechargeId error,platformOrderNo:{},sdkOrderNo:{},rechargeId:{},platformRechargeId:{},subscription:{}",
							platformOrderNo, sdkOrderNo, mallInfo.getRechargeId(), rechargeId, subscription);
					sendResult(response, 0, "dirty productId");
					return;
				}

				mallMoney = MallRechargeConfigMgr.getPrice(mallInfo);
//				long mallMoney = Long.parseLong(mallInfo.getPrice());
				if (mallMoney > amount) {//收的钱小于定价
					BigDecimal bigTax = new BigDecimal(tax);
					BigDecimal totalAmount = bigTax.multiply(BigDecimal.valueOf(100)).add(BigDecimal.valueOf(amount));
					if(0 != totalAmount.compareTo(BigDecimal.valueOf(mallMoney))){
						logger.error("subscribeRecharge amount error,platformOrderNo:{},sdkOrderNo:{},amount:{},platformAmount:{},subscription:{}",
								platformOrderNo, sdkOrderNo, mallMoney, amount, subscription);
						sendResult(response, 0, "dirty money");
						return;
					}
				}
				if(0 == returnIngots) {
					returnIngots = MallRechargeConfigMgr.getReturnIngots(mallInfo);
				}
				if(0 == vipExp){
					vipExp = (int) MallRechargeConfigMgr.getParamValue(mallInfo);
				}
				if(0 == shopType){
					shopType = mallInfo.getShopType();
				}
				if(StringUtils.isNullOrEmpty(mallName)){
					String language = UserMgr.getLanguage(userId);
					mallName = MallMgr.getMallName(mallInfo, language);
				}
				if(0 == mallMarkId){
					mallMarkId = mallInfo.getMallMarkId();
					if(0 == mallMarkId){
						mallMarkId = mallId;
					}
				}
			}

			if(null != firstRechargeOrder) {
				//校验金额
				if (firstRechargeOrder.getAmount() > amount) {//收的钱小于定价
					BigDecimal bigTax = new BigDecimal(tax);
					BigDecimal totalAmount = bigTax.multiply(BigDecimal.valueOf(100)).add(BigDecimal.valueOf(amount));
					if (0 != totalAmount.compareTo(BigDecimal.valueOf(firstRechargeOrder.getAmount()))) {
						logger.error("subscribeRecharge 预订单金额不一致orderNo:{};preAmount:{}; nowAmount:{},subscription:{}", orderNo, firstRechargeOrder.getAmount(), amount, subscription);
						sendResult(response, 0, "dirty money");
						return;
					}
				}
			}

			RechargeOrder newRechargeOrder = new RechargeOrder();
			String newOrderNo = OrderHelper.generateOrderNum();
			newRechargeOrder.setOrderNo(newOrderNo);
			if(null != firstRechargeOrder) {
				newRechargeOrder.setUserId(firstRechargeOrder.getUserId());
				newRechargeOrder.setAmount(firstRechargeOrder.getAmount());
				newRechargeOrder.setMallId(firstRechargeOrder.getMallId());
				newRechargeOrder.setPreChargeType(firstRechargeOrder.getPreChargeType());
				newRechargeOrder.setActivityId(firstRechargeOrder.getActivityId());
				newRechargeOrder.setConditionId(firstRechargeOrder.getConditionId());
				newRechargeOrder.setReturnIngots(firstRechargeOrder.getReturnIngots());
				newRechargeOrder.setAddVipExp(firstRechargeOrder.getAddVipExp());
				newRechargeOrder.setShopType(firstRechargeOrder.getShopType());
				newRechargeOrder.setMallName(firstRechargeOrder.getMallName());
				newRechargeOrder.setMallMarkId(firstRechargeOrder.getMallMarkId());
			}else {
				newRechargeOrder.setUserId(userId);
				newRechargeOrder.setAmount(mallMoney);
				newRechargeOrder.setMallId(mallId);
				newRechargeOrder.setPreChargeType(ePreChargeType.normalBuy.getValue());
				newRechargeOrder.setActivityId(0);
				newRechargeOrder.setConditionId(0);
				newRechargeOrder.setReturnIngots(returnIngots);
				newRechargeOrder.setAddVipExp(vipExp);
				newRechargeOrder.setShopType(shopType);
				newRechargeOrder.setMallName(mallName);
				newRechargeOrder.setMallMarkId(mallMarkId);
			}

			newRechargeOrder.setPlatformOrderNo(platformOrderNo);
			newRechargeOrder.setSdkOrderNo(sdkOrderNo);
			newRechargeOrder.setPayType(payType);
			newRechargeOrder.setCurrency(currency);
			newRechargeOrder.setRealMoney(realMoney);
			newRechargeOrder.setRealCurrency(realCurrency);
			newRechargeOrder.setLocalMoney(localMoney);
			newRechargeOrder.setLocalCurrency(localCurrency);
			newRechargeOrder.setLtrRate(ltrRate);
			newRechargeOrder.setNewMoney(newMoney);
			newRechargeOrder.setTax(tax);
			newRechargeOrder.setProductCoin(productCoin);
			newRechargeOrder.setDevice(device);
			newRechargeOrder.setPayChannel(payChannel);
			newRechargeOrder.setCouponMoney(couponMoney);
			newRechargeOrder.setProductType(productType);
			newRechargeOrder.setSubscription(subscription);
			newRechargeOrder.setGid(gid);
			newRechargeOrder.setAppid(appId);
			newRechargeOrder.setPayMethod(payMethod);
			newRechargeOrder.setPackageId(UserMgr.getUserPackageMark(userId));

			//游戏内到账
			newRechargeOrder.setOrderStatus(eOrderStatus.ToBeCharged);
			if (!RechargeBussiness.addRechargeOrderFull(newRechargeOrder)) {
				logger.error("subscribeRecharge add new subscribe order fail,platformOrderNo:{},sdkOrderNo:{},subscription:{}",
						platformOrderNo, sdkOrderNo, subscription);
				sendResult(response, 0, "add new subscribe order fail");
				return;

			}
			GameWebServiceInvoke.notifyRechargeSuccess(newRechargeOrder.getOrderNo(), 0);
			sendResult(response, 1, "success");
		}else if(2 == type){//取消订阅
			RechargeOrder firstRechargeOrder = RechargeBussiness.getRechargeOrderBySdkOrderNo(curSubscriptionOrderId);
			if (null == firstRechargeOrder) {
				logger.error("subscribeRecharge first order no find,platformOrderNo:{},sdkOrderNo:{},subscription:{}",
						platformOrderNo, sdkOrderNo, subscription);
				sendResult(response, 0, "order no find");
				return;
			}
			if(firstRechargeOrder.getUserId() != userId){
				logger.error("subscribeRecharge order userId error,platformOrderNo:{},sdkOrderNo:{},local userId:{},platformUserId:{},subscription:{}",
						platformOrderNo, sdkOrderNo, firstRechargeOrder.getUserId(), userId, subscription);
				sendResult(response, 0, "roleId error");
				return;
			}
			RechargeOrder lastRechargeOrder = RechargeBussiness.getRechargeOrderBySdkOrderNo(sdkOrderNo);
			if(null == lastRechargeOrder){//取消订阅必须要有上一次的订单，不然校验不通过
				logger.error("subscribeRecharge order cancel error,no find last order, platformOrderNo:{},sdkOrderNo:{},subscription:{}",
						platformOrderNo, sdkOrderNo, subscription);
				sendResult(response, 0, "subscribe error,no last order");
				return;
			}

			String cancelOrderNo = OrderHelper.getSubscribeOrderNo(sdkOrderNo);
			RechargeOrder repeatedOrder = RechargeBussiness.getRechargeOrderBySdkOrderNo(cancelOrderNo);
			if(null != repeatedOrder){//重复订单
				if(!Objects.equals(repeatedOrder.getPlatformOrderNo(), platformOrderNo)){
					logger.error("subscribeRecharge repeat notify,local platformOrderNo:{},platformOrderNo{},sdkOrderNo:{},subscription:{}",
							repeatedOrder.getPlatformOrderNo(), platformOrderNo, sdkOrderNo, subscription);
				}
				sendResult(response, 1, "success");
				return;
			}

			RechargeOrder newRechargeOrder = new RechargeOrder();
			String newOrderNo = OrderHelper.generateOrderNum();
			newRechargeOrder.setOrderNo(newOrderNo);
			newRechargeOrder.setUserId(firstRechargeOrder.getUserId());
			newRechargeOrder.setAmount(0L);				//取消订阅的订单就不要设置价格了
			newRechargeOrder.setMallId(firstRechargeOrder.getMallId());
			newRechargeOrder.setPreChargeType(firstRechargeOrder.getPreChargeType());
			newRechargeOrder.setActivityId(firstRechargeOrder.getActivityId());
			newRechargeOrder.setConditionId(firstRechargeOrder.getConditionId());
			newRechargeOrder.setReturnIngots(firstRechargeOrder.getReturnIngots());
			newRechargeOrder.setAddVipExp(firstRechargeOrder.getAddVipExp());
			newRechargeOrder.setShopType(firstRechargeOrder.getShopType());
			newRechargeOrder.setMallName(firstRechargeOrder.getMallName());
			newRechargeOrder.setMallMarkId(firstRechargeOrder.getMallMarkId());

			newRechargeOrder.setPlatformOrderNo(platformOrderNo);
			newRechargeOrder.setSdkOrderNo(sdkOrderNo);
			newRechargeOrder.setPayType(payType);
			newRechargeOrder.setCurrency(currency);
			newRechargeOrder.setRealMoney(realMoney);
			newRechargeOrder.setRealCurrency(realCurrency);
			newRechargeOrder.setLocalMoney(localMoney);
			newRechargeOrder.setLocalCurrency(localCurrency);
			newRechargeOrder.setLtrRate(ltrRate);
			newRechargeOrder.setNewMoney(newMoney);
			newRechargeOrder.setTax(tax);
			newRechargeOrder.setProductCoin(productCoin);
			newRechargeOrder.setDevice(device);
			newRechargeOrder.setPayChannel(payChannel);
			newRechargeOrder.setCouponMoney(couponMoney);
			newRechargeOrder.setProductType(productType);
			newRechargeOrder.setSubscription(subscription);
			newRechargeOrder.setGid(gid);
			newRechargeOrder.setAppid(appId);
			newRechargeOrder.setPayMethod(payMethod);
			newRechargeOrder.setPackageId(UserMgr.getUserPackageMark(userId));

			//游戏内到账
			newRechargeOrder.setOrderStatus(eOrderStatus.ToBeCharged);
			if (!RechargeBussiness.addRechargeOrderFull(newRechargeOrder)) {
				logger.error("subscribeRecharge add new subscribe order fail,platformOrderNo:{},sdkOrderNo:{},subscription:{}",
						platformOrderNo, sdkOrderNo, subscription);
				sendResult(response, 0, "add new subscribe order fail");
				return;

			}
			GameWebServiceInvoke.notifyRechargeSuccess(newRechargeOrder.getOrderNo(), 0);
			sendResult(response, 1, "success");
		}else {
			logger.error("subscribeRecharge order type error,orderNo:{},platformOrderNo:{},sdkOrderNo:{},type:{}",
					orderNo, platformOrderNo, sdkOrderNo, type);
			sendResult(response, 0, "order subscription type error");
			return;
		}
	}

	/**
	 *
	 * @param response
	 * @param platformOrderNo
	 * @param sdkOrderNo
	 * @param mallId
	 * @param productType
	 * @param amount
	 * @param ingots
	 * @param openId
	 * @param userId
	 * @param realIngots
	 * @param extraIngots
	 */
	private void thirdPartyRecharge(HttpServletResponse response, String platformOrderNo, String sdkOrderNo, int mallId, String productType, long amount,
									int ingots, String openId, long userId, int realIngots, int extraIngots, int subCoinType, String subCoinRatio, int extraCoinType, String extraCoinRatio, int rechargeId, String currency, String realMoney, String realCurrency,
									String localMoney, String localCurrency, String ltrRate, String newMoney, String tax, long productCoin, int device, String payChannel,
									String couponMoney, String gid, String appId, String payMethod) {
		if(RechargeBussiness.checkThirdPartyRechargeOrder(platformOrderNo)){
			logger.error("androidRecharge thirdPartyRecharge platformOrderNo already exist,orderNo:{}", platformOrderNo);
			sendResult(response, 1, "orderNo already exist");
			return;
		}
		//判断代币
		if(OrderHelper.isTokensOrder(sdkOrderNo)){//代币订单
			if(!TokenOrderWhiteMgr.isTokenOrderWhite(userId)){//非白名单
				logger.error("androidRecharge thirdPartyRecharge代币订单，但非白名单,orderNo:{};userId:{}", platformOrderNo, userId);
				sendResult(response, 0, "token order not white user");
				return;
			}
		}
		int channelId = ServerListMgr.getChannelId(WebServer.getInstance().getServerId());
		if(eChannelType.isTwChannel(channelId)){
			//港澳台到账处理
			thirdPartyRechargeDealTw(response, platformOrderNo, sdkOrderNo, mallId, productType, amount, ingots, userId, realIngots, extraIngots, subCoinType, subCoinRatio, extraCoinType, extraCoinRatio,
					rechargeId, currency, realMoney, realCurrency, localMoney, localCurrency, ltrRate, newMoney, tax, productCoin, device, payChannel,
					couponMoney, gid, appId, payMethod);
		}else {//非港澳台到账处理
			thirdPartyRechargeDealOther(response, platformOrderNo, sdkOrderNo, mallId, productType, amount, ingots, userId, realIngots, extraIngots, subCoinType, subCoinRatio, extraCoinType, extraCoinRatio,
					rechargeId, currency, realMoney, realCurrency, localMoney, localCurrency, ltrRate, newMoney, tax, productCoin, device, payChannel,
					couponMoney, gid, appId, payMethod);
		}
	}

	/**
	 * 处理港澳台到账
	 * @param response
	 * @param platformOrderNo
	 * @param sdkOrderNo
	 * @param mallId
	 * @param productType
	 * @param amount
	 * @param ingots
	 * @param userId
	 * @param realIngots
	 * @param extraIngots
	 */
	private void thirdPartyRechargeDealTw(HttpServletResponse response, String platformOrderNo, String sdkOrderNo, int mallId, String productType,
										  long amount, int ingots, long userId, int realIngots, int extraIngots, int subCoinType, String subCoinRatio, int extraCoinType, String extraCoinRatio, int rechargeId, String currency, String realMoney, String realCurrency,
										  String localMoney, String localCurrency, String ltrRate, String newMoney, String tax, long productCoin, int device, String payChannel,
										  String couponMoney, String gid, String appId, String payMethod) {
		int activityId = 0;
		int mallMarkId = 0;
		if(Objects.equals(eOrderProductType.Package.getValue(), productType)){
			MallInfo mallInfo = MallMgr.getMallInfoByMallId(mallId);
			if (null == mallInfo) {
				logger.error("androidRecharge thirdPartyRechargeDealTw mall no find,platformOrderNo:{}; mallId:{}", platformOrderNo, mallId);
				sendResult(response, 0, "product no find");
				return;
			}
			if (rechargeId != mallInfo.getRechargeId()) {
				logger.error("androidRecharge thirdPartyRechargeDealTw rechargeId error,platformOrderNo:{}; mallId:{}; rechargeId:{}; platformRechargeId:{}",
						platformOrderNo, mallId, mallInfo.getRechargeId(), rechargeId);
				sendResult(response, 0, "dirty productId");
				return;
			}

			long mallMoney = MallRechargeConfigMgr.getPrice(mallInfo);
//			long mallMoney = Long.parseLong(mallInfo.getPrice());
			double tempMoney = mallMoney;
			tempMoney = tempMoney * 0.9;
			long checkMoney = (long) tempMoney;
			if (checkMoney > amount) {//收的钱小于定价
				logger.error("androidRecharge thirdPartyRechargeDealTw amount error,platformOrderNo:{};amount:{}; platformAmount:{}", platformOrderNo, mallMoney, amount);
				sendResult(response, 0, "dirty money");
				return;
			}
			activityId = mallInfo.getActivityId();
			mallMarkId = mallInfo.getMallMarkId();
		}
		ThirdPartyRechargeOrder rechargeOrder = initThirdPartyRechargeOrder(platformOrderNo, sdkOrderNo, mallId, productType, amount, ingots,
				userId, realIngots, extraIngots, subCoinType, subCoinRatio, extraCoinType, extraCoinRatio, currency, realMoney, realCurrency, localMoney, localCurrency, ltrRate, newMoney, tax,
				productCoin, device, payChannel, activityId, couponMoney, mallMarkId, gid, appId, payMethod);
		if (RechargeBussiness.addThirdPartyRechargeOrder(rechargeOrder)) {
			GameWebServiceInvoke.notifyRechargeSuccess(platformOrderNo, 1);
			sendResult(response, 1, "success");
		} else {
			logger.error("androidRecharge thirdPartyRechargeDealTw add order to db fail,platformOrderNo:{}", platformOrderNo);
			sendResult(response, 0, "add order to db fail");
		}
	}

	/**
	 * 处理其他渠道的到账
	 * @param response
	 * @param platformOrderNo
	 * @param sdkOrderNo
	 * @param mallId
	 * @param productType
	 * @param amount
	 * @param ingots
	 * @param userId
	 * @param realIngots
	 * @param extraIngots
	 */
	private void thirdPartyRechargeDealOther(HttpServletResponse response, String platformOrderNo, String sdkOrderNo, int mallId, String productType,
											 long amount, int ingots, long userId, int realIngots, int extraIngots, int subCoinType, String subCoinRatio, int extraCoinType, String extraCoinRatio, int rechargeId, String currency, String realMoney, String realCurrency,
											 String localMoney, String localCurrency, String ltrRate, String newMoney, String tax, long productCoin, int device, String payChannel,
											 String couponMoney, String gid, String appId, String payMethod) {
		int activityId = 0;
		int mallMarkId = 0;
		if(mallId > 0) {//有商品，判断商品信息
			MallInfo mallInfo = MallMgr.getMallInfoByMallId(mallId);
			if (null == mallInfo) {
				logger.error("androidRecharge thirdPartyRechargeDealOther mall no find,platformOrderNo:{}; mallId:{}", platformOrderNo, mallId);
				sendResult(response, 0, "product no find");
				return;
			}
			if (rechargeId != mallInfo.getRechargeId()) {
				logger.error("androidRecharge thirdPartyRechargeDealOther rechargeId error,platformOrderNo:{}; mallId:{}; rechargeId:{}; platformRechargeId:{}",
						platformOrderNo, mallId, mallInfo.getRechargeId(), rechargeId);
				sendResult(response, 0, "dirty productId");
				return;
			}

			long mallMoney = MallRechargeConfigMgr.getPrice(mallInfo);
//			long mallMoney = Long.parseLong(mallInfo.getPrice());
			double tempMoney = mallMoney;
			int channleId = ServerListMgr.getChannelId(WebServer.getInstance().getServerId());
			if(channleId == eChannelType.Thailand.getValue() ||
					channleId == eChannelType.US.getValue() ||
					channleId == eChannelType.UK.getValue()
			){
				tempMoney = tempMoney * 0.7;
			}else {
				tempMoney = tempMoney * 0.7;
			}
			long checkMoney = (long) tempMoney;
			if (checkMoney > amount) {//商品金额大于订单总金额
				logger.error("androidRecharge thirdPartyRechargeDealOther amount error,platformOrderNo:{};amount:{}; platformAmount:{}", platformOrderNo, mallMoney, amount);
				sendResult(response, 0, "dirty money");
				return;
			}
			activityId = mallInfo.getActivityId();
			mallMarkId = mallInfo.getMallMarkId();
		}

		ThirdPartyRechargeOrder rechargeOrder = initThirdPartyRechargeOrder(platformOrderNo, sdkOrderNo, mallId, productType, amount, ingots,
				userId, realIngots, extraIngots, subCoinType, subCoinRatio, extraCoinType, extraCoinRatio, currency, realMoney, realCurrency, localMoney, localCurrency, ltrRate, newMoney, tax,
				productCoin, device, payChannel, activityId, couponMoney, mallMarkId, gid, appId, payMethod);
		if (RechargeBussiness.addThirdPartyRechargeOrder(rechargeOrder)) {
			GameWebServiceInvoke.notifyRechargeSuccess(platformOrderNo, 1);
			sendResult(response, 1, "success");
		} else {
			logger.error("androidRecharge thirdPartyRechargeDealOther add order to db fail,platformOrderNo:{}", platformOrderNo);
			sendResult(response, 0, "add order to db fail");
		}
	}

	private ThirdPartyRechargeOrder initThirdPartyRechargeOrder(String platformOrderNo, String sdkOrderNo, int mallId, String productType, long amount,
																int ingots, long userId, int realIngots, int extraIngots, int subCoinType, String subCoinRatio, int extraCoinType, String extraCoinRatio, String currency, String realMoney, String realCurrency, String localMoney,
																String localCurrency, String ltrRate, String newMoney, String tax, long productCoin, int device, String payChannel, int activityId,
																String couponMoney, int mallMarkId, String gid, String appId, String payMethod) {
		ThirdPartyRechargeOrder data = new ThirdPartyRechargeOrder();
		data.setUserId(userId);
		data.setPlatformOrderNo(platformOrderNo);
		data.setSdkOrderNo(sdkOrderNo);
		data.setAmount(amount);
		data.setIngots(ingots);
		data.setOrderStatus(eOrderStatus.ToBeCharged);
		data.setCreateTime(new Date());
		data.setUpdateTime(new Date());
		data.setMallId(mallId);
		data.setProductType(productType);
		data.setRealIngots(realIngots);
		data.setExtraIngots(extraIngots);
		data.setSubCoinType(subCoinType);
		data.setSubCoinRatio(subCoinRatio);
		data.setExtraCoinType(extraCoinType);
		data.setExtraCoinRatio(extraCoinRatio);
		data.setCurrency(currency);
		data.setRealMoney(realMoney);
		data.setRealCurrency(realCurrency);
		data.setLocalMoney(localMoney);
		data.setLocalCurrency(localCurrency);
		data.setLtrRate(ltrRate);
		data.setNewMoney(newMoney);
		data.setTax(tax);
		data.setProductCoin(productCoin);
		data.setDevice(device);
		data.setPayChannel(payChannel);
		data.setActivityId(activityId);
		data.setCouponMoney(couponMoney);
		if(OrderHelper.isTokensOrder(sdkOrderNo)){//代币订单
			data.setOrderType(1);
		}
		data.setMallMarkId(mallMarkId == 0 ? mallId : mallMarkId);
		data.setGid(gid);
		data.setAppid(appId);
		data.setPayMethod(payMethod);
		data.setPackageId(UserMgr.getUserPackageMark(userId));
		return data;
	}

	public static void main(String[] args) {
		int i = Integer.parseInt("");
		System.out.println(i);
	}
}
